package com.itchen.headline.controller;

import com.itchen.headline.common.Result;
import com.itchen.headline.common.ResultCodeEnum;
import com.itchen.headline.pojo.NewsUser;
import com.itchen.headline.service.NewsUserService;
import com.itchen.headline.service.impl.NewsUserServiceImpl;
import com.itchen.headline.util.JwtHelper;
import com.itchen.headline.util.MD5Util;
import com.itchen.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/*")
public class NewsUserController extends BaseController{

    private NewsUserService userService = new NewsUserServiceImpl();

    /**
     * 校验是否失去登录状态
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");

        Result result = Result.build(null,ResultCodeEnum.NOTLOGIN);
        if(null != token){
            if(!JwtHelper.isExpiration(token)){
                result = Result.ok(null);
            }
        }
        WebUtil.writeJson(resp,result);
    }

    /**
     * 注册的表单提交
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收用户信息（接收信息用readJson方法）
        NewsUser registUser = WebUtil.readJson(req, NewsUser.class);
        // 调用服务层接口将用户信息存入数据库
        Integer rows = userService.registUser(registUser);

        // 存入是否成功
        Result result = Result.ok(null);
        if(rows == 0){
            result = Result.build(null,ResultCodeEnum.USERNAME_USED);
        }

        WebUtil.writeJson(resp,result);
    }

    /**
     * 注册时校验用户名是否被占用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        NewsUser newsUser = userService.findByUsername(username);
        Result result = null;
        if (null == newsUser){
            result = Result.ok(null);
        }else{
            result = Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp,result);
    }

    /**
     * （重登陆时）根据 token 获取用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中的token
        String token = req.getHeader("token");

        Result result = Result.build(null,ResultCodeEnum.NOTLOGIN);

        // 校验token
        if(null != token && !"".equals(token)){
            // 判断token是否过期
            if (!JwtHelper.isExpiration(token)) {
                // 解析userId
                Integer userId = JwtHelper.getUserId(token).intValue();
                NewsUser newsUser = userService.findByUid(userId);
                if(null != newsUser){
                    Map data = new HashMap();
                    newsUser.setUserPwd("");
                    data.put("loginUser",newsUser);
                    result = Result.ok(data);
                }
            }
        }

        WebUtil.writeJson(resp,result);

    }

    /**
     * 处理登录表单提交的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收用户名、密码（实现）
        NewsUser paramUser = WebUtil.readJson(req, NewsUser.class);
        // 实现登录
        NewsUser loginUser = userService.findByUsername(paramUser.getUsername());

        Result result = null;
        if(null != loginUser){
            // 判断密码是否正确
            // paramUser.getUserPwd()  获取接受到的明文密码
            // loginUser.getUserPwd()  获取数据库查询到的密文密码
            // MD5Util.encrypt()       将接收到的明文密码转为密文密码
            // equalsIgnoreCase()      将两个密码进行不区分大小写的比对
            if (MD5Util.encrypt(paramUser.getUserPwd()).equalsIgnoreCase(loginUser.getUserPwd())) {
                // loginUser.getUid()                      获取接收到的id
                // JwtHelper.createToken(**.longValue())   将id转化为token
                // 设置专门的json字符串格式
                Map data = new HashMap();
                data.put("token",JwtHelper.createToken(loginUser.getUid().longValue()));
                result = Result.ok(data);
            }else{
                // 返回`密码错误`的状态码信息
                result = Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
            }
        }else{
            // 返回数据库`用户信息为空`的状态码信息
            result = Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        // 向客户端响应登录验证信息
        WebUtil.writeJson(resp,result);
    }
}
